<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="单据编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="单据编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="供应商" prop="supplierName" width="120"/>
      <el-table-column label="单据编号" prop="receiptNumber" :show-overflow-tooltip="true" width="180"/>
      <el-table-column label="商品信息" prop="goodsInfo" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="单据日期" prop="billDate" width="100"/>
      <el-table-column label="操作员" prop="adminName" width="100"/>
      <el-table-column label="金额合计" prop="totalAmount" width="100"/>
      <el-table-column label="支付定金" prop="depositAmount" width="100"/>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <span style="color: #13ce66" v-if="scope.row.state === 0">已审核</span>
          <span style="color: #e05858" v-else-if="scope.row.state === 1">待审核</span>
          <span style="color: #15e3f6" v-else-if="scope.row.state === 2">已入库</span>
          <span style="color: #1f1e1e" v-else-if="scope.row.state === 3">已退单</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state === 1"
          size="mini"
          type="text"
          icon="el-icon-s-promotion"
          @click="handlePass(scope.row)"
          >审核通过
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配置对话框 -->
    <el-dialog title="添加采购订单" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" :inline="true" style="width: 100%;padding: 20px">
        <el-form-item label="供应商" prop="supplierName">
          <el-select v-model="form.supplierName" placeholder="请选择供应商" size="mini">
            <el-option v-for="supplier in suppliers"
                       :key="supplier.id"
                       :value="supplier.name"
                       :label="customLabel(supplier)">
            </el-option>
          </el-select>
        </el-form-item>
        &emsp;&emsp;&emsp;
        <el-form-item>
          <el-button icon="el-icon-search" @click="showGoodsListDialog" size="mini">选择商品</el-button>
        </el-form-item>
        <div style="border-top: 1px solid #e0e0e0;margin-top:20px;margin-bottom:20px"></div>
        <el-table :data="selectGoodsList">
          <el-table-column label="名字" prop="name"/>
          <el-table-column label="规格" prop="spec"/>
          <el-table-column label="型号" prop="model"/>
          <el-table-column label="颜色" prop="color"/>
          <el-table-column label="单位" prop="unit"/>
          <el-table-column label="价格" prop="purchasePrice"/>
          <el-table-column label="数量" prop="number">
            <template slot-scope="scope">
              <el-input v-model="scope.row.number" placeholder="" size="mini" style="width: 100px"/>
            </template>
          </el-table-column>
        </el-table>
        <br/>
        <div style="width: 100%">
          <el-input type="textarea" v-model="form.note" placeholder="订单备注"/>
        </div>
        <br/>
        <el-form-item label="结算账户" prop="accountId">
          <el-select v-model="form.accountId" placeholder="请选择结算账户" size="mini">
            <el-option v-for="account in accounts"
                       :key="account.id"
                       :value="account.id"
                       :label="accountLabel(account)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单总额" prop="totalAmount" disabled="true">
          <el-input :value="calculateTotalAmount" placeholder="" size="mini" :readonly="true"/>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discountAmount">
          <el-input v-model="form.discountAmount" placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="优惠后金额" prop="realAmount" disabled="true">
          <el-input :value="calculateRealAmount" placeholder="" size="mini" :readonly="true"/>
        </el-form-item>
        <el-form-item label="支付定金" prop="depositAmount">
          <el-input v-model="form.depositAmount" placeholder="" size="mini"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定添加</el-button>
        <el-button type="primary" @click="submitForm2">添加并审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 选择商品的弹窗 -->
    <el-dialog title="选择要采购的商品" :visible.sync="goodsListOpen" width="1000px" append-to-body>
      <el-table ref="goodsTable" :data="goodsList" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="名字" prop="name"/>
        <el-table-column label="规格" prop="spec"/>
        <el-table-column label="型号" prop="model"/>
        <el-table-column label="颜色" prop="color"/>
        <el-table-column label="单位" prop="unit"/>
        <el-table-column label="价格" prop="purchasePrice"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="selectedGoodsList">确定选择</el-button>
        <el-button @click="goodsListDialogCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {addOrder, delOrder, getOrder, listOrder, passOrder, updateOrder} from "@/api/purchase/order";
import {listGoods} from "@/api/base/goods";
import {listSupplier} from "@/api/base/supplier";
import {listAccount} from "@/api/base/account";

export default {
  name: "cgorder",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      showSearch: true,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 采购订单表格数据
      orderList: [],
      //商品列表
      goodsList: [],
      suppliers: [],
      accounts: [],
      //选中的商品
      selectGoodsList: [],
      //第一个弹窗
      open: false,
      //第二个弹窗
      goodsListOpen: false,
      selectedGoods:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: ""
      },
      // 表单参数
      form: {
        note: "", // 订单备注
        supplierName: "", //供应商
        orderNo: "", //订单号
        accountId: "", //结算账户ID
        depositAmount: "", //定金
        discountAmount: "",//优惠金额
        totalAmount: "",//订单总额
        realAmount: 0, // 优惠后金额
        selectGoodsList: [],
        adminName: "",
      },
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  created() {
    this.getList();
    this.getSuppliers();
  },
  computed: {
    // 计算订单总额
    calculateTotalAmount() {
      return this.selectGoodsList.reduce((total, item) => {
        return total + (item.purchasePrice || 0) * (item.number || 0);
      }, 0);
    },
    // 计算优惠后金额
    calculateRealAmount() {
      return this.calculateTotalAmount - this.form.discountAmount;
    },
  },
  methods: {
    accountLabel(account) {
      return `${account.name} - ${account.sn}`;
    },
    customLabel(supplier) {
      return `${supplier.name} - ${supplier.phone}`;
    },
    cancel() {
      this.open = false;
    },
    goodsListDialogCancel() {
      this.goodsListOpen = false;
      this.selectGoodsList = [];
      this.$refs.goodsTable.clearSelection();
    },
    showGoodsListDialog() {
      this.goodsListOpen = true;
    },
    selectedGoodsList() {
      this.goodsListOpen = false;
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询采购商品列表 */
    getGoodsList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询供应商列表 */
    getSuppliers() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        this.suppliers = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询结算账户列表 */
    getAccounts() {
      this.loading = true;
      listAccount(this.queryParams).then(response => {
        this.accounts = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleGoodsSelectionChange(selection) {
      this.selectGoodsList = selection;
      this.form.selectGoodsList = selection;
      console.log(this.form.selectGoodsList)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.getGoodsList();
      this.getSuppliers();
      this.getAccounts();

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const order = {
            note: this.form.note,
            supplierName: this.form.supplierName,
            orderNo: this.form.orderNo,
            accountId: this.form.accountId,
            depositAmount: this.form.depositAmount,
            discountAmount: this.form.discountAmount,
            totalAmount: this.calculateTotalAmount,
            realAmount: this.calculateRealAmount,
            goods: this.form.selectGoodsList,
            adminName: this.$store.state.user.name,
            state:1
          };
            addOrder(order).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
      });
    },
    submitForm2() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const order = {
            note: this.form.note,
            supplierName: this.form.supplierName,
            orderNo: this.form.orderNo,
            accountId: this.form.accountId,
            depositAmount: this.form.depositAmount,
            discountAmount: this.form.discountAmount,
            totalAmount: this.calculateTotalAmount,
            realAmount: this.calculateRealAmount,
            goods: this.form.selectGoodsList,
            adminName: this.$store.state.user.name,
            state:0
          };
            addOrder(order).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 审核按钮操作 */
    handlePass(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认审核通过编号为"' + ids + '"的数据项？').then(function() {
        return passOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
